﻿using System;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Text;
using Texfina.Core.Common;
using Texfina.Common.Mg;
using Texfina.Core.Web;
using Texfina.Core.Data;
using Texfina.Entity.Rh;
using Texfina.Entity.Mg;
using Texfina.Entity.Sy;
using RHBOQry = Texfina.BOQry.Rh;
using MGBOQry = Texfina.BOQry.Mg;
using RHBORpt = Texfina.BORpt.Rh;
using RHBOMnt = Texfina.BOMnt.Rh;
using SYBOQry = Texfina.BOQry.Sy;
using CrystalDecisions.CrystalReports.Engine;
using System.IO;
using CrystalDecisions.Shared;

namespace RH
{
    public partial class wfPerContratoMnt : EditPage
    {
        public const int _GRDLIST_STCONTRATO = 14;
        public const int _GRDLIST_STANULADO = 15;
        public const int _GRDLIST_STCONTRAARCH = 16;


        public string _STRSTCONTRATO
        {
            get { return (string)this.ViewState["_STRSTCONTRATO"]; }
            set { this.ViewState["_STRSTCONTRATO"] = value; }
        }

        public string _STRSTPRORROGA
        {
            get { return (string)this.ViewState["_STRSTPRORROGA"]; }
            set { this.ViewState["_STRSTPRORROGA"] = value; }
        }
        public string _STARCHIVO
        {
            get { return (string)this.ViewState["_STARCHIVO"]; }
            set { this.ViewState["_STARCHIVO"] = value; }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.IsPostBack)
            {
                if (this.Request.Params["__EVENTTARGET"] == "SpliterTiempo")
                {
                    this.SpliterTiempo();
                }

                this.LoadInPostBack();
                return;
            }
            this.LoadData();
        }

        public override void LoadInPostBack()
        {
            this.RegisterGeneralScripts();
        }

        public override void LoadInitialSettings()
        {
            this.FormEditAction = (FormEditAction)Enum.Parse(typeof(FormEditAction), Request.QueryString["formEA"]);
            this.GridEditAction = GridEditAction.Edit;
            this.SetInitialTitle("Contratos");
        }

        public override void LoadListControls()
        {
            ETablaGenDet objEDet = new ETablaGenDet();
            ETablaPEDet objEDetPE = new ETablaPEDet();
            ECCosto objECCosto = new ECCosto();
            EEmpEstable objEEmp = new EEmpEstable();
            EBanco objEBanco = new EBanco();
            EModContra objEModaC = new EModContra();

            IBOQuery objBOCCosto = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(MGBOQry.CCosto));
            IBOQuery objBOBanco = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(MGBOQry.Banco));
            MGBOQry.ITablaGen objBOI = (MGBOQry.ITablaGen)WCFHelper.GetObject<MGBOQry.ITablaGen>(typeof(MGBOQry.TablaGen));
            RHBOQry.ITablaPE objBOIPE = (RHBOQry.ITablaPE)WCFHelper.GetObject<RHBOQry.ITablaPE>(typeof(RHBOQry.TablaPE));
            SYBOQry.IEmpresa objBOEmp = (SYBOQry.IEmpresa)WCFHelper.GetObject<SYBOQry.IEmpresa>(typeof(SYBOQry.Empresa));

            objEDet.IdTabla = ConstMultitabla.TIPO_DOCUMENTO;
            DataTable dt = objBOI.GetDetailByList(objEDet);
            WebHelper.LoadListControl(ddlidTDocIden, dt, "dsAbrev", "idCodigo", true, true);

            objEDet.IdTabla = ConstMultitabla.SEXO;
            dt = objBOI.GetDetailByList(objEDet);
            WebHelper.LoadListControl(ddlidSexo, dt, "dsDescrip", "idCodigo", true, true);

            objEDet.IdTabla = ConstMultitabla.MOTIVO_CESE;
            dt = objBOI.GetDetailByList(objEDet);
            WebHelper.LoadListControl(ddlidMotivFin, dt, "dsDescrip", "idCodigo", true, true);

            objEDet.IdTabla = ConstMultitabla.GRUPO_OCUPACIONES;
            dt = objBOI.GetDetailByList(objEDet);
            WebHelper.LoadListControl(ddlidGrpOcupac, dt, "dsDescrip", "idCodigo", true, true);

            objEDet.IdTabla = ConstMultitabla.TIPO_REMUNERACION_VARIABLE;
            dt = objBOI.GetDetailByList(objEDet);
            WebHelper.LoadListControl(ddlidRemVariable, dt, "dsDescrip", "idCodigo", true, true);

            objEDet.IdTabla = ConstMultitabla.TIPO_MONEDA;
            dt = objBOI.GetDetailByList(objEDet);
            WebHelper.LoadListControl(ddlidMoneda, dt, "dsDescrip", "idCodigo", true, true);

            objEDet.IdTabla = ConstMultitabla.CARGO_PERSONAL;
            dt = objBOI.GetDetailByList(objEDet);
            WebHelper.LoadListControl(ddlidPuesto, dt, "dsDescrip", "idCodigo", true, true, true);

            objEDet.IdTabla = ConstMultitabla.PERIODO_REMUNERACION;
            dt = objBOI.GetDetailByList(objEDet);
            WebHelper.LoadListControl(ddlidPeriRemu, dt, "dsDescrip", "idCodigo", true, true);

            IBOQuery objBOModaC = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(RHBOQry.ModContra));
            dt = objBOModaC.GetList(objEModaC);
            WebHelper.LoadListControl(ddlidModalidad, dt, "dsModalidad", "idModalidad", true, true);

        }

        public override void DataToControls()
        {
            EPersonal objE = new EPersonal();
            IBOQuery objBO = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(RHBOQry.Personal));
            objE.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
            objE.IdPersonal = Request.QueryString["IdPersonal"];
            objE = (EPersonal)objBO.GetByKey(objE);

            if (objE != null)
            {

                WebHelper.EntityToControl(objE, "IdPersonal", txtidPersonal);
                WebHelper.EntityToControl(objE, "FeNacimien", txtfeNacimiento);
                WebHelper.EntityToControl(objE, "IdSexo", ddlidSexo);

                ECliProv objECli = new ECliProv();
                IBOQuery objBOCli = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(MGBOQry.CliProv));
                objECli.IdCliProv = objE.IdCliProv;
                objECli = (ECliProv)objBOCli.GetByKey(objECli);

                if (objECli != null)
                {
                    WebHelper.EntityToControl(objECli, "IdCliProv", hdnidCliProv);
                    WebHelper.EntityToControl(objECli, "DsAPaterno", txtdsAPaterno);
                    WebHelper.EntityToControl(objECli, "DsAMaterno", txtdsAMaterno);
                    WebHelper.EntityToControl(objECli, "DsNombres", txtdsNombres);
                    WebHelper.EntityToControl(objECli, "IdTDocIden", ddlidTDocIden);
                    WebHelper.EntityToControl(objECli, "NuDocIden", txtnuDocIden);

                    WebHelper.EntityToControl(objECli, "NuTelf", txtnuTelf);
                    WebHelper.EntityToControl(objECli, "NuFax", txtnufax);
                    WebHelper.EntityToControl(objECli, "DsEmail", txtdsEmail);
                    WebHelper.EntityToControl(objECli, "DsWeb", txtdsWeb);

                }

            }


            EPerContrato objEDet = new EPerContrato();

            RHBOQry.IPersonal objBODet = (RHBOQry.IPersonal)WCFHelper.GetObject<RHBOQry.IPersonal>(typeof(RHBOQry.Personal));



            objEDet.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
            objEDet.IdPersonal = Request.QueryString["IdPersonal"];
            DataTable dt = objBODet.GetByParentKeyPerContrato(objEDet);

            this.GridSetDataBinding(grdList, dt);

        }

        public override void RegisterGeneralScripts()
        {
            txtidPersonal.Attributes.Add("readonly", "true");

            this.txtfeInicio.OnClientClickDay = " __doPostBack('SpliterTiempo', '');  ";
            this.txtfeFin.OnClientClickDay = " __doPostBack('SpliterTiempo', '');  ";
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("function validateEditForm(key){");
            sb.AppendLine("var varRpta = isEmptyControl('" + txtdsAPaterno.ClientID + "','Ingrese el Apellido Paterno');");
            sb.AppendLine("if(varRpta==true){");
            sb.AppendLine("document.getElementById('" + txtdsAPaterno.ClientID + "').focus();return !varRpta;}");
            sb.AppendLine("var varRpta = isEmptyControl('" + txtdsAMaterno.ClientID + "','Ingrese el Apellido Materno');");
            sb.AppendLine("if(varRpta==true){");
            sb.AppendLine("document.getElementById('" + txtdsAMaterno.ClientID + "').focus();return !varRpta;}");
            sb.AppendLine("var varRpta = isEmptyControl('" + txtdsNombres.ClientID + "','Ingrese los Nombres');");
            sb.AppendLine("if(varRpta==true){");
            sb.AppendLine("document.getElementById('" + txtdsNombres.ClientID + "').focus();return !varRpta;}");
            sb.AppendLine("var varRpta = isEmptyControl('" + ddlidTDocIden.ClientID + "','Seleccione el tipo de Documento de Identidad');");
            sb.AppendLine("if(varRpta==true){");
            sb.AppendLine("document.getElementById('" + ddlidTDocIden.ClientID + "').focus();return !varRpta;}");
            sb.AppendLine("var varRpta = isEmptyControl('" + txtnuDocIden.ClientID + "','Ingrese el numero de Documento de Identidad');");
            sb.AppendLine("if(varRpta==true){");
            sb.AppendLine("document.getElementById('" + txtnuDocIden.ClientID + "').focus();return !varRpta;}");
            sb.AppendLine("var varRpta = isEmptyControl('" + txtfeNacimiento.ClientID + "','Seleccione o ingrese la fecha de Nacimiento');");
            sb.AppendLine("if(varRpta==true){");
            sb.AppendLine("document.getElementById('" + txtfeNacimiento.ClientID + "').focus();return !varRpta;}");
            sb.AppendLine("var varRpta = isEmptyControl('" + ddlidSexo.ClientID + "','Seleccione el Genero');");
            sb.AppendLine("if(varRpta==true){");
            sb.AppendLine("document.getElementById('" + ddlidSexo.ClientID + "').focus();return !varRpta;}");
            sb.AppendLine("menu_doPostBack('" + mnuToolbar.ClientID + "','" + mnuToolbar.UniqueID + "',key);");
            sb.AppendLine("}");

            sb.AppendLine("function validateEditFormGrid(key){");
            sb.AppendLine("varRpta = gridFindCellValueInRow('" + grdList.ClientID + "',new Array(" + _GRDLIST_STCONTRATO + "," + _GRDLIST_STANULADO + "), new Array(" + ConstFlagEstado.DESACTIVADO + "," + ConstFlagEstado.DESACTIVADO + "),'Solo puede existir un contrato Activo, deshabilite los actuales.');");
            sb.AppendLine("if(varRpta==true)");
            sb.AppendLine("return !varRpta;");
            sb.AppendLine("menu_doPostBack('" + mnuGrid.ClientID + "','" + mnuGrid.UniqueID + "',key);");
            sb.AppendLine("}");

            ScriptManager.RegisterStartupScript(this, this.GetType(), "ScriptRegister", sb.ToString(), true);

            RegisterEditPopupScripts();
        }

        public void RegisterEditPopupScripts()
        {
            this.txtidContrato.Attributes.Add("readonly", "true");
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("function validate" + this.bttOkPopup.ID + "(){");
            sb.AppendLine("varRpta = isEmptyControl('" + this.txtfeSuscripcion.ClientID + "','Ingrese el fecha de Suscripcion.');");
            sb.AppendLine("if(varRpta==true)");
            sb.AppendLine("return !varRpta;");
            sb.AppendLine("varRpta = isEmptyControl('" + this.txtfeInicio.ClientID + "','Ingrese la fecha de Inicio.');");
            sb.AppendLine("if(varRpta==true)");
            sb.AppendLine("return !varRpta;");
            sb.AppendLine("varRpta = isEmptyControl('" + this.txtfeFin.ClientID + "','Ingrese la fecha Fin.');");
            sb.AppendLine("if(varRpta==true)");
            sb.AppendLine("return !varRpta;");
            if (this.GridEditAction == GridEditAction.Delete)
            {
                sb.AppendLine("varRpta = isEmptyControl('" + this.ddlidMotivFin.ClientID + "','Selecciona el motivo de Cese.');");
                sb.AppendLine("if(varRpta==true)");
                sb.AppendLine("return !varRpta;");

                sb.AppendLine("varRpta = isEmptyControl('" + this.txtfeCese.ClientID + "','Selecciona la fecha de Cese.');");
                sb.AppendLine("if(varRpta==true)");
                sb.AppendLine("return !varRpta;");
            }

            sb.AppendLine("varRpta = isEmptyControl('" + this.ddlidPuesto.ClientID + "','Seleccione el Puesto.');");
            sb.AppendLine("if(varRpta==true)");
            sb.AppendLine("return !varRpta;");
            sb.AppendLine("varRpta = isEmptyControl('" + this.txtDsFuncion.ClientID + "','Seleccione la Funcion.');");
            sb.AppendLine("if(varRpta==true)");
            sb.AppendLine("return !varRpta;");
            sb.AppendLine("varRpta = isEmptyControl('" + this.ddlidModalidad.ClientID + "','Seleccione la Modalidad.');");
            sb.AppendLine("if(varRpta==true)");
            sb.AppendLine("return !varRpta;");
            sb.AppendLine("varRpta = isEmptyControl('" + this.ddlidSubModal.ClientID + "','Seleccione la SubModalidad.');");
            sb.AppendLine("if(varRpta==true)");
            sb.AppendLine("return !varRpta;");
            sb.AppendLine("varRpta = isEmptyControl('" + this.ddlidGrpOcupac.ClientID + "','Seleccione el Grupo de Ocupacion.');");
            sb.AppendLine("if(varRpta==true)");
            sb.AppendLine("return !varRpta;");
            sb.AppendLine("varRpta = isEmptyControl('" + this.ddlidRemVariable.ClientID + "','Seleccione el tipo de Remuneracion.');");
            sb.AppendLine("if(varRpta==true)");
            sb.AppendLine("return !varRpta;");
            sb.AppendLine("varRpta = isEmptyControl('" + this.ddlidMoneda.ClientID + "','Seleccione el tipo de Moneda.');");
            sb.AppendLine("if(varRpta==true)");
            sb.AppendLine("return !varRpta;");
            sb.AppendLine("varRpta = isEmptyControl('" + this.txtmtRemunera.ClientID + "','Ingrese el monto de remuneracion.');");
            sb.AppendLine("if(varRpta==true)");
            sb.AppendLine("return !varRpta;");
            sb.AppendLine("return true;}");

            ScriptManager.RegisterStartupScript(this, this.GetType(), "validatePopup", sb.ToString(), true);

            this.bttOkPopup.OnClientClick = "return validate" + bttOkPopup.ID + "();";
            this.bttCancelPopup.OnClientClick = "$find('" + this.mdlPopup.ClientID + "').hide();return false;";

        }

        protected void mnuToolbar_MenuItemClick(Object sender, MenuEventArgs e)
        {
            if (e.Item == null)
                return;

            switch (e.Item.Value)
            {
                case ConstMenuToolbarValue.BUTTON_SAVE:
                case ConstMenuToolbarValue.BUTTON_SAVENEW:
                    if (this.FormEditAction != FormEditAction.Delete)
                        this.SaveData(e.Item.Value);
                    else
                        this.DeleteData();
                    break;

                case ConstMenuToolbarValue.BUTTON_EXIT:
                    this.Response.Redirect("wfPerContratoBnd.aspx");
                    break;

            }

        }

        protected void mnuGrid_MenuItemClick(Object sender, MenuEventArgs e)
        {
            if (e.Item == null)
                return;

            switch (e.Item.Value)
            {
                case ConstMenuToolbarValue.BUTTON_NEW:
                    this.GridEditAction = GridEditAction.AddNew;
                    _STRSTCONTRATO = ConstFlagEstado.DESACTIVADO;
                    this.lblTitlePopup.Text = "Contrato (Nuevo)";
                    this.LoadDataEditPopup(grdList, -1);
                    this.RegisterEditPopupScripts();
                    this.SpliterTiempo();
                    _STRSTPRORROGA = ConstFlagEstado.DESACTIVADO;
                    break;
            }


        }

        public void SpliterTiempo()
        {
            this.mdlPopup.Show();
            int intMaxDias = 0;
            int intFeValue = 0;
            int intFeInicio = 0;
            int intFeFin = 100;

            if (this.txtfeInicio.Text == "" || this.txtfeFin.Text == "")
            {
                intFeValue = 0;
                intFeInicio = 0;
                intFeFin = 100;
            }
            else
            {
                if (DateTime.Parse(this.txtfeInicio.Text).Date <= DateTime.Now.Date)
                {
                    if (DateTime.Now.Date <= DateTime.Parse(this.txtfeFin.Text).Date)
                    {
                        intMaxDias = DateTime.Parse(this.txtfeInicio.Text).Date.Subtract(DateTime.Parse(this.txtfeFin.Text).Date).Days;
                        intFeInicio = 0;
                        intFeFin = 100;
                        if (intMaxDias == 0)
                            intFeValue = 0;
                        else
                            intFeValue = (DateTime.Parse(this.txtfeInicio.Text).Date.Subtract(DateTime.Now.Date).Days * 100) / intMaxDias;

                    }
                    else
                    {
                        intMaxDias = DateTime.Parse(this.txtfeInicio.Text).Date.Subtract(DateTime.Parse(this.txtfeFin.Text).Date).Days;
                        intFeInicio = 0;
                        intFeFin = 100;
                        if (intMaxDias == 0)
                            intFeValue = 0;
                        else
                            intFeValue = (DateTime.Parse(this.txtfeInicio.Text).Date.Subtract(DateTime.Now.Date).Days * 100) / intMaxDias;
                    }
                }




            }



            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<div class='esdSpliterLT' style='width:510px;'>");
            sb.AppendLine("   <div class='esdSpliterLTBkgInactive' style='width:450px;'>");
            sb.AppendLine("      <div class='esdSpliterLTBkgActive' style='width:" + intFeValue + "%;' >");
            sb.AppendLine("         <div class='esdSpliterLTArrowUp'>");
            sb.AppendLine("            <div class='esdSpliterLTlblfechaUp' >");
            sb.AppendLine("               " + DateTime.Now.ToString("dd/MM/yyyy") + "  Hoy");
            sb.AppendLine("            </div>");
            sb.AppendLine("         </div>");
            sb.AppendLine("      </div>");
            sb.AppendLine("      <div class='esdSpliterLTArrowDownIni' style='left:" + intFeInicio + "%;'>");
            sb.AppendLine("         <div class='esdSpliterLTlblfechaDown' >");
            sb.AppendLine("            " + this.txtfeInicio.Text + " Fe.Inicio");
            sb.AppendLine("         </div>");
            sb.AppendLine("      </div>");
            sb.AppendLine("      <div class='esdSpliterLTArrowDownFin' style='left:" + intFeFin + "%;' >");
            sb.AppendLine("         <div class='esdSpliterLTlblfechaDown' >");
            sb.AppendLine("            " + this.txtfeFin.Text + " Fe.Fin");
            sb.AppendLine("         </div>");
            sb.AppendLine("      </div>");
            sb.AppendLine("   </div>");
            sb.AppendLine("</div>");
            liLineaTiempo.Text = sb.ToString();

        }

        protected void grdList_RowCommand(Object sender, GridViewCommandEventArgs e)
        {
            this.EditRowIndex = Convert.ToInt32(e.CommandArgument);

            switch (e.CommandName)
            {
                case ConstGridRowCommand.GRIDEDIT:
                    this.lblTitlePopup.Text = "Contrato (Editar)";
                    this.GridEditAction = GridEditAction.Edit;
                    _STRSTCONTRATO = ConstFlagEstado.DESACTIVADO;
                    this.mdlPopup.Show();
                    this.LoadDataEditPopup(grdList, this.EditRowIndex);
                    this.RegisterEditPopupScripts();
                    this.SpliterTiempo();
                    break;
                case ConstGridRowCommand.GRIDCOPY:
                    this.lblTitlePopup.Text = "Contrato (Prorroga)";
                    this.GridEditAction = GridEditAction.AddNew;
                    _STRSTCONTRATO = ConstFlagEstado.DESACTIVADO;
                    _STRSTPRORROGA = ConstFlagEstado.ACTIVADO;
                    this.mdlPopup.Show();
                    this.LoadDataEditPopup(grdList, this.EditRowIndex);
                    this.RegisterEditPopupScripts();
                    this.txtfeSuscripcion.Text = "";
                    this.txtfeInicio.Text = "";
                    this.txtfeFin.Text = "";
                    this.txtdsObservacion.Text = "";
                    this.ddlidMotivFin.SelectedIndex = 0;
                    this.SpliterTiempo();
                    break;
                case "CmdCese":
                    this.lblTitlePopup.Text = "Contrato (Cese)";
                    this.GridEditAction = GridEditAction.Edit;
                    _STRSTCONTRATO = ConstFlagEstado.ACTIVADO;
                    this.mdlPopup.Show();
                    this.LoadDataEditPopup(grdList, this.EditRowIndex);
                    this.RegisterEditPopupScripts();
                    this.SpliterTiempo();
                    break;
                case ConstGridRowCommand.GRIDPREVIEW:

                    PrintReport(ConstGridRowCommand.GRIDPREVIEW);

                    break;
                case ConstGridRowCommand.GRIDDELETE:
                    this.lblTitlePopup.Text = "Contrato (Eliminar)";
                    this.GridEditAction = GridEditAction.Delete;
                    this.mdlPopup.Show();
                    this.LoadDataEditPopup(grdList, this.EditRowIndex);
                    this.RegisterEditPopupScripts();
                    break;

                case ConstGridRowCommand.GRIDDOWLOAD:

                    DownLoadsFile(ConstGridRowCommand.GRIDPREVIEW);

                    break;
            }
        }

        protected void grdList_RowDataBound(Object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                String strRI = e.Row.RowIndex.ToString();

                ImageButton bttedit = (ImageButton)e.Row.FindControl("grdBtt" + ConstGridRowCommand.GRIDEDIT);
                ImageButton bttcese = (ImageButton)e.Row.FindControl("grdBttCmdCese");
                ImageButton bttdelete = (ImageButton)e.Row.FindControl("grdBtt" + ConstGridRowCommand.GRIDDELETE);
                ImageButton bttdowload = (ImageButton)e.Row.FindControl("grdBtt" + ConstGridRowCommand.GRIDDOWLOAD);

                bttedit.OnClientClick = "javascript:return validateGridCommands('" + ConstGridRowCommand.GRIDEDIT + "','" + strRI + "');";
                bttcese.OnClientClick = "javascript:return validateGridCommands('CmdCese','" + strRI + "');";
                bttdelete.OnClientClick = "javascript:return validateGridCommands('" + ConstGridRowCommand.GRIDDELETE + "','" + strRI + "');";
                bttdowload.OnClientClick = "javascript:return validateGridCommands('" + ConstGridRowCommand.GRIDDOWLOAD + "','" + strRI + "');";

                if (e.Row.Cells[_GRDLIST_STANULADO].Text == ConstFlagEstado.ACTIVADO)
                {
                    e.Row.ForeColor = System.Drawing.Color.Red;
                    bttedit.ImageUrl = "../Images/Icons/Disabled/Edit.png";
                    bttcese.ImageUrl = "../Images/Icons/Disabled/EditFile.png";
                    bttdelete.ImageUrl = "../Images/Icons/Disabled/Delete.png";
                }
                else
                {
                    if (e.Row.Cells[_GRDLIST_STCONTRATO].Text == ConstFlagEstado.ACTIVADO)
                    {
                        e.Row.ForeColor = System.Drawing.Color.Blue;
                        bttedit.ImageUrl = "../Images/Icons/Disabled/Edit.png";
                        bttcese.ImageUrl = "../Images/Icons/Disabled/EditFile.png";
                    }
                }
            }

        }

        protected void bttOkPopup_Click(object sender, EventArgs e)
        {

            Object objResNuSec = null;
            int intResNusec = 0;
            DataTable dt = (DataTable)this.DataSource;
            DataRow dr = null;
            dt.Columns["feCese"].AllowDBNull = true;

            if (this.GridEditAction == GridEditAction.AddNew || this.GridEditAction == GridEditAction.Copy)
            {
                objResNuSec = dt.Compute("MAX(nuSecuen)", "");
                if (objResNuSec == null || objResNuSec.ToString() == "")
                    intResNusec = 0;
                else
                    intResNusec = Convert.ToInt32(objResNuSec);
                intResNusec += 1;
                dr = dt.NewRow();
                dr["nuSecuen"] = intResNusec;
                dr["stProrroga"] = _STRSTPRORROGA;

            }
            else
            {
                dr = this.GridGetRowFromDataKey(grdList, this.EditRowIndex);
            }

            if (this.GridEditAction != GridEditAction.Delete)
            {
                dr["idEmpresa"] = Session[ConstSessionVar.EMPRESA].ToString();
                dr["idPersonal"] = Request.QueryString["IdPersonal"];
                dr["feSuscripcion"] = DateTime.Parse(this.txtfeSuscripcion.Text);
                dr["feInicio"] = DateTime.Parse(this.txtfeInicio.Text);
                dr["feFin"] = DateTime.Parse(this.txtfeFin.Text);
                dr["idMotivFin"] = this.ddlidMotivFin.SelectedItem.Value;

                  if (this.txtfeCese.Text == "")
                    dr["feCese"] = DBNull.Value;
                else

                    dr["feCese"] = DateTime.Parse(this.txtfeCese.Text);
                
                dr["dsMotivFin"] = this.ddlidMotivFin.SelectedItem.Text;
                dr["dsObservacion"] = this.txtdsObservacion.Text;
                dr["idPuesto"] = this.ddlidPuesto.SelectedItem.Value;
                dr["dsPuesto"] = this.ddlidPuesto.SelectedItem.Text;
                dr["dsFuncion"] = this.txtDsFuncion.Text;

                //dr["idFuncion"] = this.ddlidFuncion.SelectedItem.Value;

                EEmpresa objE = new EEmpresa();
                IBOQuery objBO = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(SYBOQry.Empresa));
                objE.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
                objE = (EEmpresa)objBO.GetByKey(objE);

                if (objE != null)
                {
                    dr["idRegLaboral"] = objE.IdRegLaboral;
                    dr["stMype"] = objE.StMicroEmp;
                }

                dr["stDiscapacid"] = this.rdDiscaNo.Checked == true ? ConstFlagEstado.DESACTIVADO : ConstFlagEstado.ACTIVADO;
                dr["idModalidad"] = this.ddlidModalidad.SelectedItem.Value;
                dr["dsModalidad"] = this.ddlidModalidad.SelectedItem.Text;
                dr["idSubModal"] = this.ddlidSubModal.SelectedItem.Value;
                dr["idTipo"] = Convert.ToInt32(dr["nuSecuen"]) == 1 ? ConstTipoContrato.INICIO : ConstTipoContrato.RENOVACION;
                dr["idGrpOcupac"] = this.ddlidGrpOcupac.SelectedItem.Value;
                dr["idMoneda"] = this.ddlidMoneda.SelectedItem.Value;
                dr["dsMoneda"] = this.ddlidMoneda.SelectedItem.Text;
                dr["idPeriRemu"] = this.ddlidPeriRemu.SelectedItem.Value;
                dr["mtRemunera"] = this.txtmtRemunera.Value;
                dr["idRemVariable"] = this.ddlidRemVariable.SelectedItem.Value;
                dr["stRemuEspecie"] = this.rdRemEspeNo.Checked == true ? ConstFlagEstado.DESACTIVADO : ConstFlagEstado.ACTIVADO;
                dr["stRemuMinima"] = this.rdRemMinNO.Checked == true ? ConstFlagEstado.ACTIVADO : ConstFlagEstado.DESACTIVADO;
                dr["stAnulado"] = ConstFlagEstado.DESACTIVADO;
                dr["stContrato"] = _STRSTCONTRATO;
                ///Agregado
                dr["dsAdenda"] = this.txtDsAdenda.Text;

                bool a = this.fuidContrato.HasFile;
                EPerContraArch objEArch = this.CrearEntidadArchivo();

                if (objEArch != null)
                {
                    dr["dsNombreArch"] = objEArch.DsNombreArch;
                    dr["idContrato"] = objEArch.IdContrato;
                }

            }
            else
            {
                dr["stAnulado"] = ConstFlagEstado.ACTIVADO;
            }

            if (this.GridEditAction == GridEditAction.AddNew || this.GridEditAction == GridEditAction.Copy)
            {
                dt.Rows.Add(dr);
            }


            this.GridSetDataBinding(grdList, dt);
        }

        protected void ddlidModal_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlidSubModal.Items.Clear();
            EModContraDet objEModaC = new EModContraDet();
            RHBOQry.IModContra objBOModaC = (RHBOQry.IModContra)WCFHelper.GetObject<RHBOQry.IModContra>(typeof(RHBOQry.ModContra));
            objEModaC.IdModalidad = ddlidModalidad.SelectedItem.Value;
            DataTable dt = objBOModaC.GetDetailByParentKey(objEModaC);
            WebHelper.LoadListControl(ddlidSubModal, dt, "dsSubModalidad", "idSubModalidad", true, true);
            this.mdlPopup.Show();
            this.RegisterEditPopupScripts();
        }

        public override void LoadDataEditPopup(GridView grid, int rowIndex)
        {
            this.ClearEditPopup();
            this.LockControlsPopup();

            DataRow dr = this.GridGetRowFromDataKey(this.DataSource, grdList, rowIndex);

            if (dr == null)
                return;

            WebHelper.RowToControl(dr, "feSuscripcion", txtfeSuscripcion);
            WebHelper.RowToControl(dr, "feInicio", txtfeInicio);
            WebHelper.RowToControl(dr, "feFin", txtfeFin);
            WebHelper.RowToControl(dr, "idMotivFin", ddlidMotivFin);
            WebHelper.RowToControl(dr, "dsMotivFin", ddlidMotivFin);
            WebHelper.RowToControl(dr, "dsObservacion", txtdsObservacion);

            WebHelper.RowToControl(dr, "idPuesto", ddlidPuesto);
            //WebHelper.RowToControl(dr, "dsPuesto", ddlidPuesto);
            WebHelper.RowToControl(dr, "dsFuncion", txtDsFuncion);
            //WebHelper.RowToControl(dr, "idFuncion", ddlidFuncion);

            if (dr["stDiscapacid"].ToString() == ConstFlagEstado.DESACTIVADO)
            {
                rdDiscaSi.Checked = false;
                rdDiscaNo.Checked = true;
            }
            else
            {
                rdDiscaNo.Checked = false;
                rdDiscaSi.Checked = true;
            }
            WebHelper.RowToControl(dr, "idModalidad", ddlidModalidad);

            ddlidSubModal.Items.Clear();
            EModContraDet objEModaC = new EModContraDet();
            RHBOQry.IModContra objBOModaC = (RHBOQry.IModContra)WCFHelper.GetObject<RHBOQry.IModContra>(typeof(RHBOQry.ModContra));
            objEModaC.IdModalidad = ddlidModalidad.SelectedItem.Value;
            DataTable dt = objBOModaC.GetDetailByParentKey(objEModaC);
            WebHelper.LoadListControl(ddlidSubModal, dt, "dsSubModalidad", "idSubModalidad", true, true);

            WebHelper.RowToControl(dr, "idSubModal", ddlidSubModal);
            WebHelper.RowToControl(dr, "idGrpOcupac", ddlidGrpOcupac);
            WebHelper.RowToControl(dr, "idMoneda", ddlidMoneda);
            WebHelper.RowToControl(dr, "dsMoneda", ddlidMoneda);
            WebHelper.RowToControl(dr, "idPeriRemu", ddlidPeriRemu);
            WebHelper.RowToControl(dr, "mtRemunera", txtmtRemunera);
            WebHelper.RowToControl(dr, "idRemVariable", ddlidRemVariable);

            if (dr["stRemuEspecie"].ToString() == ConstFlagEstado.DESACTIVADO)
            {
                rdRemEspeSi.Checked = false;
                rdRemEspeNo.Checked = true;
            }
            else
            {
                rdRemEspeNo.Checked = false;
                rdRemEspeSi.Checked = true;
            }
            if (dr["stRemuMinima"].ToString() == ConstFlagEstado.DESACTIVADO)
            {
                rdRemMinSI.Checked = true;
                rdRemMinNO.Checked = false;
            }
            else
            {
                rdRemMinNO.Checked = true;
                rdRemMinSI.Checked = false;
            }

            WebHelper.RowToControl(dr, "dsNombreArch", txtidContrato);

            WebHelper.RowToControl(dr, "dsAdenda", txtDsAdenda);
        }

        public new void ClearEditPopup()
        {
            this.txtfeSuscripcion.Text = "";
            this.txtfeInicio.Text = "";
            this.txtfeFin.Text = "";
            this.ddlidMotivFin.SelectedIndex = 0;
            //this.ddlidPuesto.SelectedIndex = 0;
            //this.ddlidFuncion.SelectedIndex = 0;
            this.ddlidModalidad.SelectedIndex = 0;
            this.ddlidSubModal.SelectedIndex = 0;
            this.ddlidGrpOcupac.SelectedIndex = 0;
            this.ddlidRemVariable.SelectedIndex = 0;
            this.ddlidMoneda.SelectedIndex = 0;
            this.txtmtRemunera.Value = 0;
            this.rdDiscaNo.Checked = true;
            this.rdRemEspeNo.Checked = true;
            this.rdRemMinSI.Checked = true;
            this.txtDsAdenda.Text = "";
        }

        public void LockControlsPopup()
        {
            if (this.GridEditAction == GridEditAction.Delete || _STRSTCONTRATO == ConstFlagEstado.ACTIVADO)
            {
                if (_STRSTCONTRATO == ConstFlagEstado.ACTIVADO)
                {

                    this.ddlidMotivFin.Enabled = true;
                    this.txtdsObservacion.Enabled = true;
                    this.txtfeCese.Enabled = true;
                }
                else
                {
                    this.ddlidMotivFin.Enabled = false;
                    this.txtdsObservacion.Enabled = false;
                    this.txtfeCese.Enabled = false;
                }

                this.txtfeSuscripcion.Enabled = false;
                this.txtfeInicio.Enabled = false;
                this.txtfeFin.Enabled = false;
                //this.ddlidPuesto.Enabled = false;
                //this.ddlidFuncion.Enabled = false;
                this.ddlidModalidad.Enabled = false;
                this.ddlidSubModal.Enabled = false;
                this.ddlidGrpOcupac.Enabled = false;
                this.ddlidRemVariable.Enabled = false;
                this.ddlidMoneda.Enabled = false;
                this.txtmtRemunera.Enabled = false;
                this.rdDiscaNo.Enabled = false;
                this.rdDiscaSi.Enabled = false;
                this.rdRemEspeNo.Enabled = false;
                this.rdRemEspeSi.Enabled = false;
                this.rdRemMinNO.Enabled = false;
                this.rdRemMinSI.Enabled = false;
                this.txtDsAdenda.Enabled = false;

            }
            else
            {
                this.ddlidMotivFin.Enabled = false;
                this.txtdsObservacion.Enabled = false;
                this.txtfeCese.Enabled = false;
            }
        }

        public override void SaveData(String key)
        {
            if (this.ValidateData() == false)
                return;

            IEntityBase objE = (IEntityBase)this.CreateEntitySet();
            IBOUpdate objPro = (IBOUpdate)WCFHelper.GetObject<IBOUpdate>(typeof(RHBOMnt.Personal));

            String[] strRet = objPro.UpdateData(objE);
            String strMsg = "";

            switch (this.FormEditAction)
            {

                case FormEditAction.AddNew:
                case FormEditAction.Copy:
                    strMsg = "Se ha registrado los Contratos : " + strRet[0].ToString();
                    break;
                default:
                    strMsg = "Se ha modificado los Contratos : " + txtidPersonal.Text;
                    break;
            }
            this.hdnMsgOPB.Value = this.CreatePostbackMessage(0, strMsg, "wfPerContratoBnd.aspx");
        }

        public override void DeleteData()
        {
           IEntityBase objE = (IEntityBase)this.CreateEntitySet();
           IBOUpdate objPro = (IBOUpdate)WCFHelper.GetObject<IBOUpdate>(typeof(RHBOMnt.Personal));
           objPro.DeleteData(objE);

           this.hdnMsgOPB.Value = this.CreatePostbackMessage(0, "Se anulo el derechohabiente  : " + txtidPersonal.Text, "wfPerDereHabiBnd.aspx");

        }

        public override Object CreateEntitySet()
        {


            DataTable dt = (DataTable)this.DataSource;
            this.ClearDeletedRow(this.DataSource, "stAnulado");
            IList<EPerContrato> colEContra = new List<EPerContrato>();
            IList<EPerContraArch> colEContraArch = new List<EPerContraArch>();
            RHBOQry.IPersonal objBO = (RHBOQry.IPersonal)WCFHelper.GetObject<RHBOQry.IPersonal>(typeof(RHBOQry.Personal));

            if (this.FormEditAction == FormEditAction.Delete)
            {
               foreach (DataRow dr in dt.Rows)
               {
                  this.MarkDeletedRow(dr, "stAnulado");
               }
            }

            for (int intTypeUpd = 0; intTypeUpd <= 1; intTypeUpd++)
            {
                DataTable dtChange = null;
                if (intTypeUpd == 0)
                    dtChange = dt.GetChanges(DataRowState.Added);
                else
                    dtChange = dt.GetChanges(DataRowState.Modified);


                if (dtChange != null)
                {
                    foreach (DataRow drDet in dtChange.Rows)
                    {
                        EPerContrato objEDet = DataHelper.CopyDataRowToEntity<EPerContrato>(drDet, typeof(EPerContrato));
                        EPerContraArch objEDetB = DataHelper.CopyDataRowToEntity<EPerContraArch>(drDet, typeof(EPerContraArch));

                        if (drDet.RowState == DataRowState.Added)
                        {
                            objEDet.EntityState = EntityState.Added;
                            objEDet.FeCese = null;
                            objEDetB.EntityState = EntityState.Added;

                        }
                        if (drDet.RowState == DataRowState.Modified)
                        {
                            if (objEDet.StAnulado == ConstFlagEstado.DESACTIVADO)
                            {
                                objEDet.EntityState = EntityState.Modified;
                                EPerContraArch colobjENew = new EPerContraArch();

                                colobjENew = (EPerContraArch)objBO.GetPerContraArch(objEDetB);
                                if (colobjENew != null)

                                    objEDetB.EntityState = EntityState.Modified;
                                else
                                    objEDetB.EntityState = EntityState.Added;
                            }
                            else
                            {
                                //objEDet.EntityState = EntityState.Deleted;
                                //objEDetB.EntityState = EntityState.Deleted;
                            }
                        }

                        colEContra.Add(objEDet);
                        colEContraArch.Add(objEDetB);
                    }
                }
            }

            EPersonalSet objESet = new EPersonalSet();
            objESet.ColPerContrato = colEContra;
            objESet.ColContraArch = colEContraArch;

            return objESet;
        }

        private EPerContraArch CrearEntidadArchivo()
        {

            HttpPostedFile objFile = this.fuidContrato.PostedFile;

            if (objFile == null)
                return null;

            if (objFile.ContentLength == 0)
                return null;

            //byte[] objStream = new byte[objFile.ContentLength];
            //objFile.InputStream.Read(objStream, 0, objFile.ContentLength);
            //objFile.InputStream.Close();

            // byte[] objStream = this.GetNewByteImage(this.fuidFotografia);

            byte[] objStream = new byte[objFile.ContentLength];
            objFile.InputStream.Read(objStream, 0, objFile.ContentLength);


            objFile.InputStream.Close();

            EPerContraArch objEArch = new EPerContraArch();

            if (_STARCHIVO == ConstFlagEstado.DESACTIVADO)
                objEArch.EntityState = EntityState.Added;
            else
                objEArch.EntityState = EntityState.Modified;

            objEArch.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
            objEArch.IdPersonal = txtidPersonal.Text;
            objEArch.DsNombreArch = Path.GetFileName(objFile.FileName);
            objEArch.IdContrato = objStream;

            return objEArch;

        }
        
        public override void LockControls()
        {
            //if (this.FormEditAction == FormEditAction.Delete)
            //else  
        }

        protected void grdBttCmdPrevPostBackDataBinding(Object sender, EventArgs e)
        {
            ImageButton ctl = (ImageButton)sender;
            ScriptManager sm = ScriptManager.GetCurrent(this.Page);
            sm.RegisterPostBackControl(ctl);
        }

        public override void PrintReport(string key)
        {
            ReportDocument objRpt = new ReportDocument();

            DataSet ds = (DataSet)this.GetDataReport(key);

            string strIdTipoTrab = ds.Tables[0].Rows[0]["idTipoTrab"].ToString();
            string strStProrroga = ds.Tables[0].Rows[0]["stProrroga"].ToString();
            string strStRemuMinima = ds.Tables[0].Rows[0]["stRemuMinima"].ToString();

            string strMsg = "";


            switch (strIdTipoTrab)
            {
                case ConstTipoTrabajador.EMPLEADO:

                    if (strStProrroga == ConstFlagEstado.DESACTIVADO)
                    {
                        objRpt.Load(this.MapPath(ConstSistema.ROOT_FOLDER_PATH + "/Contratos.rpt"));
                    }

                    else
                    {
                        objRpt.Load(this.MapPath(ConstSistema.ROOT_FOLDER_PATH + "/Contratos2.rpt"));
                    }

                    break;

                case ConstTipoTrabajador.OBRERO:

                    if (strStProrroga == ConstFlagEstado.DESACTIVADO)
                    {
                        objRpt.Load(this.MapPath(ConstSistema.ROOT_FOLDER_PATH + "/ContratoObrero.rpt"));
                        break;
                    }

                    if (strStProrroga == ConstFlagEstado.ACTIVADO && strStRemuMinima == ConstFlagEstado.ACTIVADO)
                    {
                        objRpt.Load(this.MapPath(ConstSistema.ROOT_FOLDER_PATH + "/ContratoObrero2.rpt"));
                        break;
                    }
                    if (strStProrroga == ConstFlagEstado.ACTIVADO && strStRemuMinima == ConstFlagEstado.DESACTIVADO)
                    {
                        objRpt.Load(this.MapPath(ConstSistema.ROOT_FOLDER_PATH + "/ContratoObrero3.rpt"));
                        break;
                    }
                    break;


                default:
                    strMsg = "No tiene Registros";
                    this.hdnMsgOPB.Value = this.CreatePostbackMessage(0, strMsg, "");
                    break;
            }


            objRpt.SetDataSource(ds.Tables[0]);

            MemoryStream ms = new MemoryStream();

            Response.Clear();

            ms = (MemoryStream)objRpt.ExportToStream(ExportFormatType.PortableDocFormat);
            objRpt.Dispose();
            objRpt = null;

            Response.AddHeader("Content-Disposition", "attachment;filename=CONTRATO.pdf");

            Response.Buffer = true;
            Response.ContentType = "application/pdf";

            ms.WriteTo(Response.OutputStream);
            Response.Flush();
            Response.End();

        }

        private void DownLoadsFile(string key)
        {
            EPerContraArch objE = (EPerContraArch)this.GetDataDownLoads(key);
            if (objE != null)
            {
                Response.Clear();

                byte[] bArray = objE.IdContrato;
                Response.ContentType = "application/pdf";
                Response.AddHeader("content-disposition", "attachment;filename=" + objE.DsNombreArch);
                Response.BinaryWrite(bArray);
                Response.End();

            }

        }

        private object GetDataDownLoads(string key)
        {
            EPerContraArch objE = new EPerContraArch();
            RHBOQry.IPersonal objBO = (RHBOQry.IPersonal)WCFHelper.GetObject<RHBOQry.IPersonal>(typeof(RHBOQry.Personal));
            objE.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
            objE.IdPersonal = Request.QueryString["IdPersonal"];

            DataRow dr = this.GridGetRowFromDataKey(grdList, this.EditRowIndex);
            objE.NuSecuen = int.Parse(dr["nuSecuen"].ToString());
            objE = (EPerContraArch)objBO.GetPerContraArch(objE);


            return objE;
        }

        public override void ExportReport(string key)
        {
            DataSet ds = (DataSet)this.GetDataReport(key);
            ExcelHelper.ToExcel(ds, "Data.xls", Response);
        }

        public override object GetDataReport(string key)
        {
            EPerContrato objEDet = new EPerContrato();
            RHBORpt.IPersonal objBODet = (RHBORpt.IPersonal)WCFHelper.GetObject<RHBORpt.IPersonal>(typeof(RHBORpt.Personal));
            objEDet.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
            objEDet.IdPersonal = Request.QueryString["IdPersonal"];

            DataRow dr = this.GridGetRowFromDataKey(grdList, this.EditRowIndex);
            objEDet.NuSecuen = int.Parse(dr["nuSecuen"].ToString());

            DataTable dt = objBODet.GetPerContrato(objEDet);

            DataSet ds = new DataSet();
            ds.Tables.Add(dt);

            return ds;

        }


    }
}